package com.zj.leetcode.easy.hash;

import java.util.HashSet;

/**
 * @program: algorithm
 * @description: 快乐数
 * 202 happy-number
 * @author: Zhang Bo
 * @create: 2022-01-14 17:05
 **/
public class HappyNumber {
    public static void main(String[] args) {
//        int n = 19;
        int n = 2;
        Solution solution = new HappyNumber().new Solution();
        System.out.println(solution.isHappy01(n));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public boolean isHappy(int n) {

            int num = n;
            HashSet<Integer> set = new HashSet<>();
            while (num != 1) {
                num = getNum(num);
                if (set.contains(num)) {
                    return false;
                }
                set.add(num);
            }
            return true;
        }

        public int getNum(int n) {
            int num = n;
            int ret = 0;
            while (num > 0) {
                int temp = num % 10;
                ret = temp * temp + ret;
                num = num / 10;
            }
            return ret;
        }

        /**
         * 弗洛伊德循环查找算法
         *
         * @param n
         * @return
         */
        public boolean isHappy01(int n) {

            int slow = n;
            int fast = getNum(n);
            while (fast != 1 && fast != slow) {
                slow = getNum(slow);
                fast = getNum(getNum(fast));
            }
            return fast == 1;
        }

    }
//leetcode submit region end(Prohibit modification and deletion)

}
